const express = require('express')
const router = express.Router()
const { getRandom, mySend } = require('../utils/index')
const { sendCodeSms } = require('../utils/smsCode/smsCode')
const Redis = require('../redis/Redis')
const User = require('../db/model/UserModel')

router.post('/', (req, res) => {
    const { phone } = req.body
    if (!(/^1[3456789]\d{9}$/.test(phone))) {
        return mySend(res, 1, '手机号不正确')
    }
    let code = getRandom(100000, 999999)
    Redis.set(phone, code, 60 * 10).then((result) => {
        if (result !== 'OK') {
            return mySend(res, -1, '存入redis有误', result)
        }
        sendCodeSms(phone, code)
            .then(body => {
                if (body.return_code === '00000') {
                    return mySend(res, 0, '短信发送成功,有效期10分钟')
                } else {
                    return mySend(res, 1, '发送失败', body)
                }
            })
            .catch(error => {
                return mySend(res, -1, '服务器发送短信有误', error)
            })
    }).catch(err => {
        return mySend(res, -1, '存入redis有误', err)
    })

})

router.post('/getCodeByUsername', (req, res) => {
    const { username } = req.body
    if (!username) {
        return mySend(res, 1, '请输入用户名或手机号')
    }
    User.findOne({ $or: [{ username }, { phone: username }] }).then(doc => {
        if (!doc) {
            return mySend(res, 1, '用户名或手机号不存在')
        }
        const {phone} = doc
        let code = getRandom(100000, 999999)
        Redis.set(phone, code, 60 * 10).then((result) => {
            if (result !== 'OK') {
                return mySend(res, -1, '存入redis有误', result)
            }
            sendCodeSms(phone, code)
                .then(body => {
                    if (body.return_code === '00000') {
                        return mySend(res, 0, '短信发送成功,有效期10分钟')
                    } else {
                        return mySend(res, 1, '发送失败', body)
                    }
                })
                .catch(error => {
                    return mySend(res, -1, '服务器发送短信有误', error)
                })
        }).catch(err => {
            return mySend(res, -1, '存入redis有误', err)
        })
    })


})

module.exports = router